package com.power.algorithm;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * @description:
 * @author: jiangnan
 * @time: 2021/6/17 2:25 下午
 * 给定一个整数数组，判断是否存在重复元素。
 * <p>
 * 如果存在一值在数组中出现至少两次，函数返回 true 。如果数组中每个元素都不相同，则返回 false 。
 */
public class Solution217 {

    public boolean containsDuplicate(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for (int i = 0; i < nums.length; i++) {
            set.add(nums[i]);
        }
        return set.size() != nums.length;
    }

    //两个循环直接超时操作
    public boolean containsDuplicate2(int[] nums) {
        int fast = 1, slow = 0;
        while (slow < nums.length) {
            while (fast < nums.length) {
                if (nums[slow] == nums[fast]) {
                    return true;
                }
                fast++;
            }
            slow++;
            fast = slow + 1;
        }
        return false;
    }

    //先排序 然后进行判定相邻的元素
    public boolean containsDuplicate3(int[] nums) {
        Arrays.sort(nums);

        for (int i = 0; i < nums.length-1; i++) {
            if (nums[i] == nums[i + 1]) {
                return true;
            }
        }
        return false;
    }


    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4, 5,4};
        Solution217 solution217 = new Solution217();
      //  System.out.println(solution217.containsDuplicate2(nums));
        // System.out.println(solution217.containsDuplicate(nums));
        System.out.println(solution217.containsDuplicate3(nums));
    }
}
